package com.cqc.appusagestatistics01;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 获取app使用统计的情况
 * 1 首先需要 权限
 * 2 需要manager,通过manager获取所哟app的使用情况
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private RecyclerView mRecyclerView;
    //    private List<UsageStats> mList = new ArrayList<>();
    private PackageManager packageManager;
    private MyAdapter adapter;
    private Button btn;
    private Spinner spinner;
    private UsageStatsManager usageStatsManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(MainActivity.this, LinearLayoutManager.VERTICAL));
        adapter = new MyAdapter();
        mRecyclerView.setAdapter(adapter);


        packageManager = getPackageManager();
        usageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);

        btn = (Button) findViewById(R.id.btn_usage);
        spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setAdapter(ArrayAdapter.createFromResource(MainActivity.this, R.array.time_span, android.R.layout.simple_spinner_dropdown_item));
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                String text = (String) adapterView.getItemAtPosition(position);
                int intervalType = UsageStatsManager.INTERVAL_DAILY;
                switch (text) {
                    case "Daily":
                        intervalType = UsageStatsManager.INTERVAL_DAILY;
                        break;
                    case "Weekly":
                        intervalType = UsageStatsManager.INTERVAL_WEEKLY;
                        break;
                    case "Monthly":
                        intervalType = UsageStatsManager.INTERVAL_MONTHLY;
                        break;
                    case "Yearly":
                        intervalType = UsageStatsManager.INTERVAL_YEARLY;
                        break;
                }
                ToastUtil.showLongToast(MainActivity.this, "按照" + text + "排序");
                List<UsageStats> usageStatsList = getUsageStatsList(intervalType);
                Collections.sort(usageStatsList, new ComparatorList());
                adapter.setCustomUsageStatsList(usageStatsList);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    public List<UsageStats> getUsageStatsList(int intervalStyle) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -5);
        // queryUsageStats API>=21   UsageStatsManager.INTERVAL_DAILY
        List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(intervalStyle, calendar.getTimeInMillis(), System.currentTimeMillis());
        if (null == usageStatsList || usageStatsList.size() == 0) {
            ToastUtil.showLongToast(this, "UsageStatsManager==null，可能是没有给予权限");
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
                }
            });
            return null;
        }
        return usageStatsList;
    }

    public class ComparatorList implements Comparator<UsageStats> {
        @Override
        public int compare(UsageStats t1, UsageStats t2) {
            return (int) (t2.getLastTimeUsed() - t1.getLastTimeUsed());
        }
    }

    public class MyAdapter extends RecyclerView.Adapter {
        List<UsageStats> mCustomUsageStatsList = new ArrayList<>();

        public void setCustomUsageStatsList(List<UsageStats> customUsageStats) {
            mCustomUsageStatsList = customUsageStats;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

            MyViewHolder holder = (MyViewHolder) viewHolder;
            UsageStats usageStats = mCustomUsageStatsList.get(position);
            try {
                holder.iv_app_icon.setBackground(packageManager.getApplicationIcon(usageStats.getPackageName()));
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                holder.iv_app_icon.setBackgroundResource(R.mipmap.ic_launcher_round);
            }
            holder.tv_app_name.setText(usageStats.getPackageName());

            //            String dateTime = DateUtils.formatDateTime(MainActivity.this, usageStats.getLastTimeUsed(), DateUtils.FORMAT_SHOW_YEAR);
            String dateTime = DateUtils.formatDateTime(MainActivity.this, usageStats.getLastTimeUsed(), DateUtils.FORMAT_NO_MONTH_DAY);
            holder.tv_app_last_use_time.setText(dateTime);
        }

        @Override
        public int getItemCount() {
            return mCustomUsageStatsList.size();
        }
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_app_icon;
        TextView tv_app_name;
        TextView tv_app_last_use_time;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv_app_icon = (ImageView) itemView.findViewById(R.id.iv_app_icon);
            tv_app_name = (TextView) itemView.findViewById(R.id.tv_app_name);
            tv_app_last_use_time = (TextView) itemView.findViewById(R.id.tv_app_last_use_time);
        }
    }
}
